package com.hpli.domain.strategy.service.rule.chain.impl;


import com.hpli.domain.strategy.repository.IStrategyRepository;
import com.hpli.domain.strategy.service.armory.IStrategyDispatch;
import com.hpli.domain.strategy.service.rule.chain.AbstractLogicChain;
import com.hpli.domain.strategy.service.rule.chain.factory.DefaultChainFactory;
import com.hpli.types.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Author: 汀
 * @CreateTime: 2025-03-25
 * @Description: 根据抽奖权重返回可抽奖范围key
 * @Version: 1.0
 */

@Slf4j
@Component("rule_weight")
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class RuleWeightLogicChain extends AbstractLogicChain {

    @Resource
    private IStrategyRepository repository;

    @Resource
    protected IStrategyDispatch strategyDispatch;

    private final IAnalytical analytical = new AnalyticalNotEqual();


    @Override
    public DefaultChainFactory.StrategyAwardVO logic(String userId, Long strategyId) {
        log.info("规则责任链-权重开始 userId:{} strategyId:{} ruleModel:{}", userId, strategyId, ruleModel());

        String ruleValue = repository.queryStrategyRuleValue(strategyId, ruleModel());

        Map<Integer, String> analyticalValueGroup = getAnalyticalValueGroup(ruleValue);
        if (null == analyticalValueGroup || analyticalValueGroup.isEmpty()) {
            log.warn("抽奖责任链-权重告警【策略配置权重，但ruleValue未配置对应值】 userId: {} strategyId: {} ruleModel: {}"
                    , userId, strategyId, ruleModel());
            return next().logic(userId, strategyId);
        }

        Integer userScore = repository.queryActivityAccountTotalUseCount(userId, strategyId);

        String analyticalValue = analytical.getAnalyticalValue(analyticalValueGroup, userScore);

        if (null != analyticalValue) {
            Integer awardId = strategyDispatch.getRandomAwardId(strategyId, analyticalValue);
            log.info("抽奖责任链-权重接管 userId:{} strategyId:{} ruleModel:{} awardId:{}", userId, strategyId, ruleModel(), awardId);
            return DefaultChainFactory.StrategyAwardVO.builder()
                    .awardId(awardId)
                    .logicModel(ruleModel())
                    .build();
        }

        log.info("抽奖责任链-权重放行 userId:{} strategyId:{} ruleModel:{}", userId, strategyId, ruleModel());
        return next().logic(userId, strategyId);
    }

    private Map<Integer, String> getAnalyticalValueGroup(String ruleValue) {
        String[] ruleValueGroups = ruleValue.split(Constants.SPACE);
        Map<Integer, String> analyticalValueGroup = new HashMap<>();
        for (String ruleValueGroup : ruleValueGroups) {
            if (ruleValueGroup == null || ruleValueGroup.isEmpty()) {
                return analyticalValueGroup;
            }

            String[] parts = ruleValueGroup.split(Constants.COLON);
            if (parts.length != 2) {
                throw new IllegalArgumentException("rule_weight rule_rule invalid input format" + ruleValueGroup);
            }
            analyticalValueGroup.put(Integer.parseInt(parts[0]), ruleValueGroup);
        }
        return analyticalValueGroup;
    }

    @Override
    protected String ruleModel() {
        return DefaultChainFactory.LogicModel.RULE_WEIGHT.getCode();
    }

    interface IAnalytical {
        String getAnalyticalValue(Map<Integer, String> analyticalValueGroup, Integer userScore);
    }

    static class AnalyticalEqual implements IAnalytical {
        @Override
        public String getAnalyticalValue(Map<Integer, String> analyticalValueGroup, Integer userScore) {
            return analyticalValueGroup.get(userScore);
        }
    }

    static class AnalyticalNotEqual implements IAnalytical {
        @Override
        public String getAnalyticalValue(Map<Integer, String> analyticalValueGroup, Integer userScore) {
            List<Integer> analyticalSortedKeys = new ArrayList<>(analyticalValueGroup.keySet());
            Collections.sort(analyticalSortedKeys);

            Integer nextValue = analyticalSortedKeys.stream()
                    .sorted(Comparator.reverseOrder())
                    .filter(analyticalSortedKeyValue -> userScore >= analyticalSortedKeyValue)
                    .findFirst()
                    .orElse(null);

            return analyticalValueGroup.get(nextValue);
        }
    }
}
